package com.heima.kafka.sample;

import org.apache.kafka.clients.producer.internals.Sender;
import org.apache.kafka.common.serialization.Serde;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.TimeWindows;
import org.apache.kafka.streams.kstream.ValueMapper;

import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

/**
 * 流式计算
 */
public class KafkaStreamQuickStart {

    public static void main(String[] args) {

        //kafka配置
        Properties properties = new Properties();
        properties.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.200.130:9092");
        //消息的转换器
        properties.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        properties.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        //应用名称
        properties.put(StreamsConfig.APPLICATION_ID_CONFIG,"stream-app");

        //创建streamsBuilder
        StreamsBuilder streamsBuilder = new StreamsBuilder();

        //流式计算
        streamProcessor(streamsBuilder);

        //创建kafkaStream对象
        KafkaStreams kafkaStreams = new KafkaStreams(streamsBuilder.build(),properties);

        //开启流式计算
        kafkaStreams.start();
    }

    /**
     * 流式计算
     * 统计单词的个数
     * hello kafka
     * hello itcast
     */

    private static void streamProcessor(StreamsBuilder streamsBuilder) {
        //创建KStream对象，并接收消息
        KStream<String, String> stream = streamsBuilder.stream("itcast-input-topic");

        //流式计算分析
        stream.flatMapValues(new ValueMapper<String, Iterable<String>>() {
            @Override
            public Iterable<String> apply(String value) {
                String[] split = value.split(" ");
                return Arrays.asList(split);
            }
        })
                //分组
                .groupBy((key,value)->value)
                //时间窗口，可以设置窗口大小
                .windowedBy(TimeWindows.of(Duration.ofSeconds(10)))
                //count之后，key和value会有变化  key:消息的值  vlaue：统计之后的数值
                .count()
                //转换为KStream
                .toStream()
                .map((key,value)->{
                    System.out.println("消息的key:"+key.key().toString()+",value:"+value.toString());
                    return new KeyValue<>(key.key().toString(),value.toString());
                })
                //处理完数据之后，发送给某一个topic
                .to("itcast-out-topic");
    }
}
